package com.dana.redis.config;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


//因为springboot已经提供了RedisConfig的配置,这个注解的作用就是优先加载我们自己的redisconfig
@AutoConfigureBefore(RedisAutoConfiguration.class)

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();

        //用于连接redis的连接工厂
        template.setConnectionFactory(connectionFactory);

        JsonRedisSerializer serializer = new JsonRedisSerializer(Object.class);

        // 使⽤StringRedisSerializer来序列化和反序列化redis的key值
        //使用StringRedisSerializer，将key序列化为字符串
        template.setKeySerializer(new StringRedisSerializer());
        //使用自定义的JsonRedisSerializer，将value序列化为JSON
        template.setValueSerializer(serializer);


        // Hash的key也采⽤StringRedisSerializer的序列化⽅式
        //使用StringRedisSerializer，将key序列化为字符串
        template.setHashKeySerializer(new StringRedisSerializer());
        //使用自定义的JsonRedisSerializer，将value序列化为JSON
        template.setHashValueSerializer(serializer);
        //确保所有属性设置完成后进行初始化
        template.afterPropertiesSet();
        return template;
    }
}
